package com.mccken.rapid.core.context;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import lombok.Data;

/**
 * @program: rapid_gateway
 * @description:
 * @author: mccken
 * @create: 2022-01-29 16:09
 **/
@Data
public class Rule implements Comparable<Rule>, Serializable {
	
	// 规则id, 全局唯一
	private String id;
	
	// 规则名称
	private String name;
	
	// 规则对应的协议
	private String protocol;
	
	// 规则排序，用于以后万一有需求做一个路径绑定多种规则，但是只能最终执行一个规则(按照该属性做优先级判断)
	private Integer order;
	
	// 规则集合定义
	private Set<Rule.FilterConfig> filterConfigs = new HashSet<>();
	
	@Override
	public int compareTo(Rule o) {
		int orderCompare = Integer.compare(getOrder(), o.getOrder());
		
		if (orderCompare == 0) {
			return getId().compareTo(o.getId());
		}
		return orderCompare;
	}
	
	public boolean addFilterConfig(Rule.FilterConfig filterConfig) {
		return filterConfigs.add(filterConfig);
	}
	
	// 通过指定的filterId，获取FilterConfig
	public Rule.FilterConfig getFilterConfig(String id) {
		for (FilterConfig filterConfig : filterConfigs) {
			if (filterConfig.getId().equalsIgnoreCase(id)) {
				return filterConfig;
			}
		}
		return null;
	}
	
	public boolean hasId(String id) {
		FilterConfig filterConfig = getFilterConfig(id);
		return filterConfig != null;
	}
		
	
	
	// 规则的过滤器
	@Data
	public static class FilterConfig {
		// 过滤器的唯一ID
		private String id;
		
		// 过滤器的配置信息描述
		private String config;
		
		@Override
		public boolean equals(Object o) {
			if (this == o) {
				return true;
			}
			
			if (o == null || getClass() != o.getClass()) {
				return false;
			}
			
			FilterConfig that = (FilterConfig) o;
			return id.equals(that.id);
		}
		
		@Override
		public int hashCode() {
			return Objects.hash(id);
		}
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}

		if (o == null || getClass() != o.getClass()) {
			return false;
		}

		Rule that = (Rule) o;
		return id.equals(that.id);
	}

	@Override
	public int hashCode() {
		return Objects.hash(id);
	}
}
